/***************************************************
File:           LPK_TrackingCameraObject.cs
Authors:        Christopher Onorati
Last Updated:   5/21/2019
Last Version:   2018.3.14

Description:
  This component allows for an object to be added to a
  dynamic tracking system for a camera in 2D gameplay.
  This will work with perspective or orthogonal cameras.

This script is a basic and generic implementation of its 
functionality. It is designed for educational purposes and 
aimed at helping beginners.

Copyright 2018-2019, DigiPen Institute of Technology
***************************************************/

using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

namespace LPK
{

/**
* CLASS NAME  : LPK_TrackingCamereaInstantaneousObjectManager
* DESCRIPTION : Keep track of game objects cameras should be tracking.
**/
static class LPK_TrackingCamereaInstantaneousObjectManager
{
    //List of all game objects to track.
    static public List<GameObject> m_pGameObjects = new List<GameObject>();
    static public List<float> m_pWeights = new List<float>();

    /**
     * FUNCTION NAME: OnStart
     * DESCRIPTION  : Addan object to the track list.
     * INPUTS       : _addGameObject - Game object to potentially add to be tracked.
     * OUTPUTS      : None
     **/
    static public void AddObject(GameObject _addGameObject, float _weight)
    {
        if (m_pGameObjects.Contains(_addGameObject))
            return;

        m_pGameObjects.Add(_addGameObject);
        m_pWeights.Add(_weight);
    }

     /**
     * FUNCTION NAME: RemoveObject
     * DESCRIPTION  : Remove an object from the track list.
     * INPUTS       : _removeGameObject - Object to potentially remove to be tracked.
     * OUTPUTS      : None
     **/
    static public void RemoveObject(GameObject _removeGameObject)
    {
        int location = -1;

        for (int i = 0; i < m_pGameObjects.Count; i++)
        {
            if (m_pGameObjects[i] == _removeGameObject)
            {
                location = i;
                break;
            }
        }

        //Unable to find the object.
        if (location == -1)
            return;

        m_pGameObjects.RemoveAt(location);
        m_pWeights.RemoveAt(location);
    }
}

/**
* CLASS NAME  : LPK_TrackingCameraObject
* DESCRIPTION : Used to communicate to the game that an important object exists.
**/
[RequireComponent(typeof(Transform))]
public class LPK_TrackingCameraObject : LPK_Component
{
    /************************************************************************************/

    public enum LPK_ObjectTrackType
    {
        INSTANTANEOUS,
        DISTANCE,
        VIEWPORT,
    };

    /************************************************************************************/

    [Header("Component Properties")]

    [Tooltip("Marks the different add styles for important objects.")]
    [Rename("Tracking Type")]
    public LPK_ObjectTrackType m_eTrackingType = LPK_ObjectTrackType.INSTANTANEOUS;

    public float m_flImportanceWeight = 1.0f;

    public float m_flMaxAddDistance;

    /************************************************************************************/

    bool m_bHasBeenAdded = false;

    /************************************************************************************/

    Transform m_cTransform;

    /**
    * FUNCTION NAME: OnStart
    * DESCRIPTION  : Manage initial event hookup.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    override protected void OnStart()
    {
        m_cTransform = GetComponent<Transform>();

        //Adding the object to the Camera's array regardless of position.
        if (m_eTrackingType== LPK_ObjectTrackType.INSTANTANEOUS)
            LPK_TrackingCamereaInstantaneousObjectManager.AddObject(gameObject, m_flImportanceWeight);
    }

    /**
    * FUNCTION NAME: TrackingCameraMove
    * DESCRIPTION  : Checks the object's location relative to the camera's location for adding and removing objects.
    * INPUTS       : _camera         - Camera that is checking if it should track this game object.
    *                _cameraLocation - Location of the aforementioned camera.
    * OUTPUTS      : None
    **/
    public void TrackingCameraMoved(LPK_TrackingCamera _camera, Vector3 _cameraLocation)
    {
        Vector2 obj1 = new Vector2(m_cTransform.position.x, m_cTransform.position.y);
        Vector2 obj2 = new Vector2(_cameraLocation.x, _cameraLocation.y);
        
        //Adds the object to the imporant camera.
        if(Vector2.Distance(obj1, obj2) <= m_flMaxAddDistance && !m_bHasBeenAdded)
            AddObject(_camera);
        
        //Removes the object if it was added but is now out of distance.
        else if(Vector2.Distance(obj1, obj2) > m_flMaxAddDistance && m_bHasBeenAdded)
            RemoveObject(_camera);
    }

    /**
    * FUNCTION NAME: DetectVisibility
    * DESCRIPTION  : Adds and removes objects from the camera's list of objects to track based on visibility in the viewport.
    * INPUTS       : _camera         - Camera that is checking if it should track this game object.
    * OUTPUTS      : None
    **/
    public void DetectVisibility(LPK_TrackingCamera _camera)
    {
        //Adding the object to the list of objects to track.
        if (GetComponent<Renderer>() && GetComponent<Renderer>().isVisible && !m_bHasBeenAdded)
            AddObject(_camera);

        //Removing the object from the camera's list of objects to track.
        else if(GetComponent<Renderer>() && !GetComponent<Renderer>().isVisible && m_bHasBeenAdded)
            RemoveObject(_camera);
    }

    /**
    * FUNCTION NAME: AddObject
    * DESCRIPTION  : Adds an object to the camera tracker.
    * INPUTS       : _camera - Camera to add the game object to be tracked on.
    * OUTPUTS      : None
    **/
    void AddObject(LPK_TrackingCamera _camera) 
    {
        if (m_bPrintDebug)
            LPK_PrintDebug(this, "Attempting to add object to dynamic camera.");

        m_bHasBeenAdded = true;

        _camera.AddImportantObject(gameObject, m_flImportanceWeight);
    }

    /**
    * FUNCTION NAME: RemoveObject
    * DESCRIPTION  : Removes an object from the camera tracker.
    * INPUTS       : _camera - Camera to remove the object from being tracked on.
    * OUTPUTS      : None
    **/
    void RemoveObject(LPK_TrackingCamera _camera)
    {
        if (m_bPrintDebug)
            LPK_PrintDebug(this, "Attempting to remove object to dynamic camera.");

        m_bHasBeenAdded = false;

        _camera.RemoveImportantObject(gameObject);
    }

    /**
    * FUNCTION NAME: OnDestroyed
    * DESCRIPTION  : Used to remove instantaneously tracked game objects.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    void OnDestroy()
    {
        LPK_TrackingCamereaInstantaneousObjectManager.RemoveObject(gameObject);
    }
}

#if UNITY_EDITOR

[CustomEditor(typeof(LPK_TrackingCameraObject))]
public class LPK_TrackingCameraObjectEditor : Editor
{
    SerializedProperty trackingType;

    /**
    * FUNCTION NAME: OnEnable
    * DESCRIPTION  : Save out serialized classes.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    void OnEnable()
    {
        trackingType = serializedObject.FindProperty("m_eTrackingType");
    }

    /**
    * FUNCTION NAME: OnInspectorGUI
    * DESCRIPTION  : Override GUI for inspector.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    public override void OnInspectorGUI()
    {
        LPK_TrackingCameraObject owner = (LPK_TrackingCameraObject)target;

        LPK_TrackingCameraObject editorOwner = owner.GetComponent<LPK_TrackingCameraObject>();

        EditorGUI.BeginDisabledGroup(true);
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.PrefixLabel("Script");
        editorOwner = (LPK_TrackingCameraObject)EditorGUILayout.ObjectField(editorOwner, typeof(LPK_TrackingCameraObject), false);
        GUILayout.EndHorizontal();
        EditorGUI.EndDisabledGroup();

        //Undo saving.
        Undo.RecordObject(owner, "Property changes on LPK_TrackingCameraObject");

        //Component properties.
        GUILayout.Space(10);
        EditorGUILayout.LabelField("Component Properties", EditorStyles.boldLabel);

        EditorGUILayout.PropertyField(trackingType, true);
        owner.m_flImportanceWeight = EditorGUILayout.FloatField(new GUIContent("Importance Factor", "Weight of the object's importance towards the camera."), owner.m_flImportanceWeight);
        
        if(owner.m_eTrackingType == LPK_TrackingCameraObject.LPK_ObjectTrackType.DISTANCE)
            owner.m_flMaxAddDistance = EditorGUILayout.FloatField(new GUIContent("Max Add Distance", "Distance at which to add objects to the camera."), owner.m_flMaxAddDistance);

        //Debug properties.
        GUILayout.Space(10);
        EditorGUILayout.LabelField("Debug Properties", EditorStyles.boldLabel);

        owner.m_bPrintDebug = EditorGUILayout.Toggle(new GUIContent("Print Debug Info", "Toggle console debug messages."), owner.m_bPrintDebug);
        owner.m_sLabel = EditorGUILayout.TextField(new GUIContent("Label", "Notes for the user about this component.  This does nothing to the game or build."), owner.m_sLabel);
        
        //Apply changes.
        serializedObject.ApplyModifiedProperties();
    }
}

#endif  //UNITY_EDITOR

}   //LPK
